package edu.ccut.saturn.studio.wfg.command;

import java.util.Iterator;

import org.eclipse.gef.commands.Command;

import edu.ccut.saturn.studio.wfg.model.Connection;
import edu.ccut.saturn.studio.wfg.model.Shape;

public class ConnectionCreateCommand extends Command {
	private static final String CONNECTION_CREATE_COMMAND_CONNECTION_CREATION = "connection creation";
	private Connection connection;
	private final int lineStyle;
	private final Shape source;
	private Shape target;
	
	public ConnectionCreateCommand(Shape source, int lineStyle) {
		if (source == null) {
			throw new IllegalArgumentException();
		}
		setLabel(CONNECTION_CREATE_COMMAND_CONNECTION_CREATION);
		this.source = source;
		this.lineStyle = lineStyle;
	}

	public boolean canExecute() {
		for (Iterator<Connection> iter = source.getSourceConnections()
				.iterator(); iter.hasNext();) {
			Connection conn = (Connection) iter.next();
			if (conn.getTarget().equals(target)) {
				return false ;
			}
		}
		
		return true;
	}

	public void execute() {
		connection = new Connection(source, target, lineStyle);
	}
	
	public void redo() {
		connection.reconnect();
	}

	public void setTarget(Shape target) {
		if (target == null) {
			throw new IllegalArgumentException();
		}
		this.target = target;
	}

	public void undo() {
		connection.disconnect();
	}
}
